import store from '@/store'
import tool from '@/utils/tool'

export default {
    downloadFile(name) {
        store.commit('setLoading')
        const fileUrl = import.meta.env.VITE_FILE_URL
        const fileObj = JSON.parse(tool.data.get('FLIE_LIST_UPLOAD'))
        let key = ''
        switch (name) {
            case '用户手册':
                key = 'TEMPLATE_URL_INSTRUCTIONS'
                break;
            case '项目计划书':
                key = 'TEMPLATE_URL_TEMPLATE'
                break;
            case '测试环境测试报告':
                key = 'TEMPLATE_URL_PROVE'
                break;
            case '生产环境测试报告':
                key = 'TEMPLATE_URL_SCTEST'
                break;
            case '安全扫描报告':
                key = 'TEMPLATE_URL_SCANREPORT'
                break;
            case '操作手册':
                key = 'TEMPLATE_URL_TESTINSTRUCTIONS'
                break;
            default:
                break;
        }
        const path = fileObj[key].includes('http://') ? fileObj[key] : `${fileUrl}/${fileObj[key]}`
        const suffix = fileObj[key].split('.')[1]
        const xhr = new XMLHttpRequest()
        xhr.open('get', path)
        xhr.setRequestHeader('Token', tool.data.get('TOKEN'))
        xhr.responseType = 'blob'
        xhr.send()
        xhr.onload = function () {
            if (this.status === 200 || this.status === 304) {
                const fileReader = new FileReader()
                fileReader.readAsDataURL(this.response)
                fileReader.onload = function () {
                    const a = document.createElement('a')
                    a.style.display = 'none'
                    a.href = this.result
                    a.download = name + '.' + suffix
                    document.body.appendChild(a)
                    a.click()
                    document.body.removeChild(a)
                    store.commit('setLoading')
                }
            }
        }
    }
}